package cn.yunbamboos.rest.service.auth;

import cn.yunbamboos.Const;
import cn.yunbamboos.rest.service.auth.event.AuthenticationEvent;
import cn.yunbamboos.token.IToken;
import cn.yunbamboos.token.ITokenContainer;
import cn.yunbamboos.token.TokenBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 默认的权限认证监听
 * */
public class AuthenticationListener implements IAuthenticationListener {

    private static final Logger logger = LoggerFactory.getLogger(IAuthenticationListener.class);

    private final ITokenContainer tokenContainer;

    public AuthenticationListener(ITokenContainer tokenContainer) {
        this.tokenContainer = tokenContainer;
    }

    @Override
    public boolean auth(AuthenticationEvent event) {
        return event.getHeader(Const.TOKEN_KEY)
                .or(() -> event.getParameter(Const.TOKEN_KEY))
                .flatMap(tokenContainer::get).map(tokenStr -> {
                    try {
                        IToken token = new TokenBuilder().parse(tokenStr, Const.TOKEN_SECRET);
                        token.forEach((key, value) -> event.setSession(key, String.valueOf(value)));
                        return true;
                    } catch (Exception e) {
                        logger.error("read token error", e);
                    }
                    return false;
                }).orElse(false);
    }

}
